<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-+0n0xVW2eSR5OomGNYDnhzAbDsOXxcvSN1TPprVMTNDbiYZCxYbOOl7+AMvyTG2x" crossorigin="anonymous">

    <title>表格管理</title>
  </head>
  <body>
    <div class="container">
        <h1>表格管理</h1>
        <button type="button" class="btn btn-primary" onclick="list();">查询</button>
        <button type="button" class="btn btn-info" onclick="add();">新增</button>
        <table class="table">
            <thead>
              <tr>
                <th scope="col">主键</th>
                <th scope="col">姓名</th>
                <th scope="col">操作</th>
              </tr>
            </thead>
            <tbody id="table-body">
            </tbody>
          </table>
    </div>

    <div class="dialogs">
        <!-- Modal -->
        <div class="modal fade" id="saveDialog" tabindex="-1" aria-labelledby="saveDialogLabel" aria-hidden="true">
            <div class="modal-dialog">
              <div class="modal-content">
                <div class="modal-header">
                  <h5 class="modal-title" id="saveDialogLabel">保存</h5>
                  <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                  <form>
                    <input type="hidden" name="id">
                    <div class="mb-3">
                      <label for="saveDialog-name" class="col-form-label">姓名:</label>
                      <input type="text" class="form-control" id="saveDialog-name" name="name">
                    </div>
                  </form>
                </div>
                <div class="modal-footer">
                  <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                  <button type="button" class="btn btn-primary saveBtn" onclick="saveInfo()">保存</button>
                </div>
              </div>
            </div>
        </div>

        <div class="modal fade" id="deleteDialog" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="deleteDialogLabel" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="deleteDialogLabel">确认删除对话框</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <p>删除？</p>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary deleteBtn" data-bs-id="" onclick="deleteInfo(this)" >确认</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Modal -->
        <div class="modal fade" id="messageDialog" tabindex="-1" aria-labelledby="messageModalLabel" aria-hidden="true">
            <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                <h5 class="modal-title" id="messageModalLabel">提示消息对话框</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>提示消息</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-gtEjrD/SeCtmISkJkNUaaKMoLD0//ElJ19smozuHV6z3Iehds+3Ulb9Bn9Plx0x4" crossorigin="anonymous"></script>
  
    <script src="https://cdn.bootcss.com/mustache.js/2.3.0/mustache.js"></script>

    <script id="table-template" type="x-tmpl-mustache">
        {{ #list }}
        <tr>
            <td>{{id}}</td>
            <td>{{name}}</td>
            <td>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#saveDialog" data-bs-title="编辑" data-bs-id="{{id}}" data-bs-name="{{name}}">编辑</button>
                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#deleteDialog" data-bs-title="删除" data-bs-content="确定删除吗？" data-bs-id="{{id}}">
                    删除
                </button>
            </td>
        </tr>
        {{ /list }}
    </script>

    
    <script>
        // 对话框
        const saveDialog = document.getElementById('saveDialog')
        const modalSaveDialog = new bootstrap.Modal(saveDialog);
        const deleteDialog = document.getElementById('deleteDialog')
        const modalDeleteDialog = new bootstrap.Modal(deleteDialog);
        const messageDialog = document.getElementById('messageDialog')
        const modalMessageDialog = new bootstrap.Modal(messageDialog);

        saveDialog.addEventListener('show.bs.modal', function (event) {
            // Button that triggered the modal. 若调用modalSaveDialog.show()，则event.relatedTarget是undefined
            var button = event.relatedTarget
            if(button == undefined){
                return
            }
            // Extract info from data-bs-* attributes
            var title = button.getAttribute('data-bs-title')
            var id = button.getAttribute('data-bs-id')
            var name = button.getAttribute('data-bs-name')
            // If necessary, you could initiate an AJAX request here
            // and then do the updating in a callback.
            //
            // Update the modal's content.
            var modalTitle = saveDialog.querySelector('.modal-title')
            var modalIdInput = saveDialog.querySelector('.modal-body [name="id"]')
            var modalNameInput = saveDialog.querySelector('.modal-body [name="name"]')

            modalTitle.textContent = title
            modalIdInput.value = id
            modalNameInput.value = name
        })

        deleteDialog.addEventListener('show.bs.modal', function (event) {
            // Button that triggered the modal
            var button = event.relatedTarget
            // Extract info from data-bs-* attributes
            var title = button.getAttribute('data-bs-title')
            var content = button.getAttribute('data-bs-content')
            // If necessary, you could initiate an AJAX request here
            // and then do the updating in a callback.
            //
            // Update the modal's content.
            var modalTitle = deleteDialog.querySelector('.modal-title')
            var modalBodyInput = deleteDialog.querySelector('.modal-body p')

            modalTitle.textContent = title
            modalBodyInput.textContent = content

            var modalDeleteBtn = deleteDialog.querySelector('.deleteBtn')
            modalDeleteBtn.setAttribute('data-bs-id', button.getAttribute('data-bs-id'))
        })
    </script>

    <script>
        const tableTemplate = document.getElementById('table-template').innerHTML
        const tableBody = document.getElementById('table-body')
        var tableData = [] // 保存表格数据
        // 查询表格数据
        var list = function(){
            // TODO 请求后端接口获得数据
            setTimeout(function(){
                tableData = [
                        {
                            id: Math.round(Math.random())*10,
                            name: '浦口'
                        },
                        {
                            id: Math.round(Math.random())*10 + 20,
                            name: '六合'
                        },
                        {
                            id: Math.round(Math.random())*10 + 30,
                            name: '建邺'
                        },
                        {
                            id: Math.round(Math.random())*10 + 40,
                            name: '江宁'
                        },
                    ]
                loadTable()
            }, 100)
        }

        var loadTable = function(){
            var str = Mustache.render(tableTemplate, {
                list: tableData
            })
            tableBody.innerHTML = str
            console.log(str)
        }

        var add = function(){
            resetSaveDialog()
            modalSaveDialog.show()
        }

        var resetSaveDialog = function(){
            var modalIdInput = saveDialog.querySelector('.modal-body [name="id"]')
            var modalNameInput = saveDialog.querySelector('.modal-body [name="name"]')
            modalIdInput.value = ''
            modalNameInput.value = ''
        }

        var saveInfo = function(){
            var modalIdInput = saveDialog.querySelector('.modal-body [name="id"]')
            var modalNameInput = saveDialog.querySelector('.modal-body [name="name"]')
            var id = parseInt(modalIdInput.value)
            var name = modalNameInput.value
            if(!id){
                // 新增
                // 模拟请求后端接口，耗时100ms
                setTimeout(function(){
                    // 注意，这里不要重复创建new bootstrap.Modal(saveDialog)，否则失效
                    modalSaveDialog.hide()
                    // 显示提示消息对话框
                    showMessageDialog('新增'+id+'成功')
                    // 刷新表格
                    tableData.push({
                        id: new Date().getSeconds(), 
                        name: name
                    })
                    loadTable()
                }, 100)
            }else{
                // 修改
                // 模拟请求后端接口，耗时100ms
                setTimeout(function(){
                    // 注意，这里不要重复创建new bootstrap.Modal(saveDialog)，否则失效
                    modalSaveDialog.hide()
                    // 显示提示消息对话框
                    showMessageDialog('修改'+id+'成功')
                    // 刷新表格
                    tableData.map(function(ele, index, array){
                    　　// ele -> 数组中正在处理的当前元素
                    　　// index -> 数组中正在处理的当前元素的索引
                    　　// array -> 指向map方法被调用的数组
                        if(id === ele.id){
                            ele.name = name
                        }
                    })
                    loadTable()
                }, 100)
            }
        }
        
    </script>

    <script>
        var deleteInfo = function(element){
            var id = element.getAttribute('data-bs-id')
            // 模拟请求后端接口，耗时100ms
            setTimeout(function(){
                // 注意，这里不要重复创建new bootstrap.Modal(deleteDialog)，否则失效
                modalDeleteDialog.hide()
                // 显示提示消息对话框
                showMessageDialog('删除'+id+'成功')
                // 刷新表格
                list()
            }, 100)
        }

        function showMessageDialog(content){
            var modalBodyInput = messageDialog.querySelector('.modal-body p')
            modalBodyInput.textContent = content
            modalMessageDialog.show()
        }
    </script>

  </body>
</html>